package com.first.nell.components.dialog

import android.os.Bundle
import android.view.*
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.first.nell.R
import com.first.nell.databinding.AlterImageSelectBinding

class ImagePickerDialog : DialogFragment() {

    companion object {
        fun showDialog(
            fragmentManager: FragmentManager,
            listener: (Int) -> Unit = {},
        ) {
            val dialog = ImagePickerDialog()
            dialog.mOnActionListener = listener
            dialog.showNow(fragmentManager, ImagePickerDialog::class.java.simpleName)
        }
    }

    private lateinit var mViewBinding: AlterImageSelectBinding
    private var mOnActionListener: (Int) -> Unit = {}

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE)

        mViewBinding = AlterImageSelectBinding.inflate(layoutInflater)
        return mViewBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initSubViews()
        dialog?.setCancelable(true)
        dialog?.setCanceledOnTouchOutside(true)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_TITLE, R.style.Dialog)
    }

    override fun onStart() {
        super.onStart()

        dialog?.window?.let {
            it.attributes.gravity = Gravity.CENTER
            it.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        }
    }

    private fun initSubViews() {
        mViewBinding.imageDialogClose.setOnClickListener { dismiss() }
        mViewBinding.llTakePicBg.setOnClickListener {
            mOnActionListener.invoke(0)
            dismiss()
        }

        mViewBinding.llAlbumBg.setOnClickListener {
            mOnActionListener.invoke(1)
            dismiss()
        }
    }
}